package cn.learn.validate.sms;

import cn.learn.properties.MySecurityConstants;
import cn.learn.properties.SecurityProperties;
import cn.learn.validate.ValidateCode;
import cn.learn.validate.ValidateCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * 短信验证码生成器
 *
 * @author huangyezhan
 * @date 2020年02月20日22:52
 */
@Component
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public ValidateCode generate(HttpServletRequest request) {
        String  s      = request.getParameter("count");
        Integer count  = s != null ? Integer.valueOf(s) : null;
        String  random = getRandom(count);
        //获取手机号码, 手机号码的参数名称
        String paramName   = MySecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE;
        String phoneNumber = request.getParameter(paramName);

        SmsCode smsCode = new SmsCode(random,
                securityProperties.getCode().getSms().getExpireIn(),
                securityProperties.getCode().getSms().getTotalValidations(),
                securityProperties.getCode().getSms().getMsg(),
                securityProperties.getCode().getSms().getIntervalTime()
        );
        smsCode.setPhoneNumber(phoneNumber);
        return smsCode;
    }

    /**
     * @param count 生成随机数字的位数，一般是4、6位
     * @return 输出字符串数字
     */
    private String getRandom(Integer count) {
        Random        random          = new Random();
        StringBuilder sb              = new StringBuilder();
        int           propertiesCount = securityProperties.getCode().getSms().getCount();
        int           num             = (count != null && count > 0) ? count : propertiesCount;
        for (int i = 0; i < num; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }


}
